#! /bin/bash
Q1="Please provide the AP path"
Q2="Please provide the MP path"
Q3="Which partition to flash"

ANSWER=""

function msg_input()
{
    echo $1
    read ANSWER
    if [ "$2" = "true" ];then
        ANSWER="` tr '[a-z]' '[A-Z]' <<< $ANSWER`"
    fi
}

msg_input "$Q1" "false"
AP_PATH="$ANSWER"
msg_input "$Q2" "false"
MP_PATH="$ANSWER"
msg_input "$Q3" "true"
PARTITION="$ANSWER"

if [ ! -d "$AP_PATH" -o ! -d "$MP_PATH" ];then
    echo "Path not available"
    exit 1
fi    

RAW_FILE_CONTENTS=`cat $AP_PATH/rawprogram0.xml`
if [ -z "$RAW_FILE_CONTENTS" ];then
    echo "rawprogram0 is not available"
    exit 1
fi

function process_one_line()
{
    local items
    local count
    local value
    local i

    items="file_sector_offset filename label num_partition_sectors physical_partition_number size_in_KB sparse start_byte_hex start_sector"

    if [ -z "$1" ];then
        return
    fi

    echo "$1" | grep "$2" 1>/dev/null
    if [ $? -ne 0 ];then
        return
    fi

    count=`echo "$items" | wc -w`
    i=1

    while [ $i -le $count ];do
        item=`echo "$items" | cut -f $i -d ' '`
        value=`echo $1 | sed -n "s/.*${item}=\([^ ]*\) .*/\1/p"`
        echo -n "$item=$value "
        i=$(($i+1))
    done
    echo ""
}


IFS=$'\x0A'
if [ "$PARTITION" = "all" ];then
    for line in $RAW_FILE_CONTENTS;do
        process_one_line "$line" "zeroout"
    done

    for line in $RAW_FILE_CONTENTS;do
        process_one_line "$line" "program"
    done

    for line in $RAW_FILE_CONTENTS;do
        process_one_line "$line" "patch"
    done
else
    for line in $RAW_FILE_CONTENTS;do
        process_one_line "$line" "$program"    
    done

fi
    
